<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
/**
 * Class Order
 * Desc  订单控制器
 * Create on 2024/10/22 9:44
 * Create by wangyafang
 */

namespace app\api\controller\wddj\usert;


use addons\wddj\library\Wxapp;
use app\admin\model\detection\Lists;
use app\admin\model\detection\Orders;
use app\api\model\wddj\Chat;
use app\api\model\wddj\Config;
use app\api\model\wddj\trailer\CommissionRatio;
use app\api\model\wddj\trailer\Driver;
use app\api\model\wddj\User;
use app\api\model\wddj\usert\evaluation\Evaluation;
use app\api\model\wddj\usert\operation\CostAllocation;
use app\api\model\wddj\usert\Payments;
use app\api\model\wddj\usert\Refunds;
use app\api\model\wddj\WaitingTime;
use app\common\controller\Api;
use app\common\model\Category;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Order extends Api
{
    protected $noNeedLogin = ['notify','notify_bak','checkNotify'];
    protected $noNeedRight = ['create','index','cancel','details','pending_count','cost_inquiry','awaiting_payment','backDiving'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wddj\usert\Order();
    }

    /**
     * Desc 创建订单
     * Create on 2024/10/22 9:50
     * Create by wangyafang
     */
    public function create()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->post();
        $cityObj = (new \app\api\model\wddj\usert\operation\City())->where('city','like','%'.$param['city'].'%')->find();
        if (empty($cityObj)) {
            $this->error('城市没有开通拖车服务');
        }
        $param['city_id'] = $cityObj['id'];

        $result = $this->validate($param,'app\api\validate\wddj\usert\Order');
        if(true !== $result){
            // 验证失败 输出错误信息
            $this->error($result);
        }

        $wechat_id = User::getWechatId($this->auth->id);
        $real_name_authentication_status = (new Config())->where('id',1)->value('real_name_authentication_status');
        if ($real_name_authentication_status == '1') {
            $where['wechat_id'] = array('eq',$wechat_id);
            $userRealNameAuthenticationObj = (new \app\api\model\wddj\usert\UserRealNameAuthentication())->where($where)->find();
            if (!$userRealNameAuthenticationObj) {
                $this->error('请先到安全中心，进行实名认证');
            }
        }
        $awaitingPaymentOrderObj = $this->model->where('wechat_id',$wechat_id)->where('state','awaiting_payment')->find();
        if ($awaitingPaymentOrderObj) {
            $this->error('有待补差订单未付款');
        }
        $out_trade_no = $order_no = wddj_create_order();
        $city_id = $param['city_id'];
        $from_lat = $param['from_lat'];//出发地纬度
        $from_lng = $param['from_lng'];
        $to_lat = $param['to_lat'];
        $to_lng = $param['to_lng'];
        $estimated_amount = cache('city_id'.$city_id.'from_lat'.$from_lat.'from_lng'.$from_lng.'to_lat'.$to_lat.'to_lng'.$to_lng);
        $mapResult = (new Map())->get_driver_routes($param);
        if (empty($estimated_amount)) {
            $estimated_amount_result = \app\api\model\wddj\usert\operation\CostAllocation::estimated_amount($city_id,$mapResult['result']['routes'][0]['distance']);
            $estimated_amount = $estimated_amount_result['estimated_amount'];
        }
        $commissionRatioObj = (new CommissionRatio())->where('city_id',$city_id)->find();
        if (empty($commissionRatioObj)) {
            $this->error('城市未配置抽成比例，无法下单');
        }
        $pay_amount = bcmul($estimated_amount,$param['driver_number'],2);
        $estimated_amount = bcmul($estimated_amount,$param['driver_number'],2);
        $create_data = array(
            'wechat_id'=>$wechat_id,
            'order_no'=>$order_no,
            'estimated_amount'=>$estimated_amount,
            'pay_amount'=>$pay_amount,
            'driving_distance'=>bcdiv($mapResult['result']['routes'][0]['distance'],1000,2),
            'driving_distance_meter'=>$mapResult['result']['routes'][0]['distance'],
            'travel_time'=>$mapResult['result']['routes'][0]['duration'],
            'actual_meter'=>$mapResult['result']['routes'][0]['distance'],
            'actual_amount'=>$estimated_amount,
        );
        $create_data = array_merge($create_data,$param);
        if (!isset($param['remarks'])) {
            $create_data['remarks'] = '';
        }

        $paymentsModel = new Payments();
        Db::startTrans();
        try {
            $this->model->data($create_data);
            $this->model->allowField(true)->save();
            $payments_data = array(
                'order_id'=>$this->model->id,
                'out_trade_no'=>$out_trade_no,
                'pay_amount'=>$pay_amount,
                'payment_type'=>'prepaid',
                'payment_status'=>'unpaid',
            );
            $paymentsModel->data($payments_data);
            $paymentsModel->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        cache('city_id'.$city_id.'from_lat'.$from_lat.'from_lng'.$from_lng.'to_lat'.$to_lat.'to_lng'.$to_lng,NULL);


        try {
            $openid = wddj_get_openid($wechat_id);
            $conf = Wxapp::unify('下单', $out_trade_no, $estimated_amount, $openid, request()->domain() . '/api/wddj/usert/order/notify');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('微信预支付调用成功',array(
            'id'=>$this->model->id,
            'conf'=>$conf,
        ));
    }

    /**
     * Desc 待补差微信预支付调用
     * Create on 2024/12/14 10:31
     * Create by wangyafang
     */
    public function awaiting_payment()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $id = $this->request->post('id');
        $orderObj = $this->model->get($id);
        if (!$orderObj) {
            $this->error('订单不存在');
        }
        if ($orderObj['state'] != 'awaiting_payment') {
            $this->error('不是待补差订单');
        }


        $out_trade_no = wddj_create_order();


        Db::startTrans();
        try {
            $orderObj->order_no = $out_trade_no;


            $orderObj->save();
            $payments_data = array(
                'order_id'=>$id,
                'out_trade_no'=>$out_trade_no,
                'pay_amount'=>abs($orderObj['adjust_amount']),
                'payment_type'=>'prepaid',
                'payment_status'=>'unpaid',
            );
            $paymentsModel = new Payments();
            $paymentsModel->data($payments_data);
            $paymentsModel->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        try {
            $openid = wddj_get_openid($orderObj['wechat_id']);
            $conf = Wxapp::unify('待补差', $out_trade_no, abs($orderObj['adjust_amount']), $openid, request()->domain() . '/api/wddj/usert/order/notify');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('微信预支付调用成功',array(
            'id'=>1,
            'conf'=>$conf,
        ));
    }

    /**
     * Desc 订单支付回调
     * Create on 2024/10/22 9:51
     * Create by wangyafang
     */
    public function notify()
    {
        $pay = \addons\wddj\library\Wxapp::getPay();
        $response = $pay->handlePaidNotify(function($message, $fail){
            $paymentsModel = new Payments();
            $paymentsObj = $paymentsModel->where('out_trade_no',$message['out_trade_no'])->find();
            if (!$paymentsObj || $paymentsObj['payment_status'] == 'completed') {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    $this->notify_inner($message['out_trade_no'],$paymentsObj);
                }
            } else {
                return $fail('FAIL');
            }

            return true;
        });

        $response->send();
    }

    /**
     * Desc 车检订单支付回调
     * Create on 2024/10/22 9:51
     * Create by maomao
     */
    public function checkNotify()
    {
        $pay = \addons\wddj\library\Wxapp::getPay();
        $response = $pay->handlePaidNotify(function($message, $fail){
            if ($message['return_code'] === 'SUCCESS') {
                if ($message['result_code'] === 'SUCCESS') {
                    //先处理检测订单相关逻辑
                    $checkOrder = new Orders();
                    $order = $checkOrder->where(['numbers'=>$message['out_trade_no']])->find();
                    if(empty($order) || $order->status != 0)
                        return true;

                    $order->status = 1;
                    $order->paytime = time();
                    $order->pay_amount = $message['total_fee'] / 100;
                    $order->pay_orderid = $message['transaction_id'];
                    $order->save();
                    if($order->is_diving == 1)
                    {

                        $paymentsModel = new Payments();
                        $paymentsObj = $paymentsModel->where('out_trade_no',$order['out_trade_no'])->find();
                        if (!$paymentsObj || $paymentsObj['payment_status'] == 'completed') {
                            return true;
                        }
                        $this->notify_inner($order['out_trade_no'],$paymentsObj);
                    }
                }
            } else {
                return $fail('FAIL');
            }

            return true;
        });

        $response->send();
    }
    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 检测结束--拖车送回车辆
     */
    public function backDiving()
    {
        $orderId = $this->request->post('orderId');
        $params = $this->request->post();
        if(!$orderId)
            $this->error($this->warningMsg);
        $order = Orders::get($orderId);
//        if($order->status != 3)
//            $this->error($this->errorMsg = '订单未结束');
        if($order->back_numbers){
            $check = db('wddj_order')->where(['order_no'=>$order->back_numbers])->value('state');
            if($check != 'cancelled')
                $this->error($this->errorMsg = '请勿重复下单');
        }
        $wddj_order = db('wddj_order')->where(['order_no'=>$order->out_trade_no])->find();
        $wechat_id = User::getWechatId($order['userid']);
        $store = Lists::find($order['end_storeid']);
        $vehicle_info = Category::get(['name'=>$order['vehicle_type']]);
        //订单封装
        $key = (new \app\api\model\wddj\Config())->where('id',1)->value('tencent_map_web_service_key');
        $city_result = getAddress($wddj_order['from_lat'], $wddj_order['from_lng'],$key);
        $store_result = getAddress($store->latitude, $store->longitude,$key);
        if(!$city_result || !$store_result)
            throw new Exception('位置信息获取失败');
        //下拖车订单
        $car_order = [
            'type'=> 2,
            'city'=>  $city_result['city'],
            'to_city'=>($store_result['province'].'/'.$store_result['city'].'/'.$store_result['district']),
            'city_type'=>$vehicle_info->pid,//城市拖车规则中的车辆类型
            'to_address'=> $wddj_order['from_address'],
            'to_lat'=> $wddj_order['from_lat'],
            'to_lng'=> $wddj_order['from_lng'],
            'from_address'=> $store->address,
            'from_lat'=> $store->latitude,
            'from_lng'=> $store->longitude,
            'driver_number'=> 1,
            'departure_time'=> $wddj_order['check_over_time'],
            'is_back'=>1
        ];
        Db::startTrans();
        try {
            $order_result = \app\api\model\wddj\usert\Order::autoCreate($car_order,$wechat_id);
            if(!is_array($order_result))
                throw new Exception($order_result);
            $order->back_numbers = $order_result['out_trade_no'];
            $order->save();
//            $openid = wddj_get_openid($wechat_id);
//            $estimated_amount = 0.01;
            //        $estimated_amount = $order_result['estimated_amount'];
//            $conf = Wxapp::unify('下单', $order_result['out_trade_no'], $estimated_amount, $openid, request()->domain() . '/api/wddj/usert/order/notify');
            $paymentsModel = new Payments();
            $paymentsObj = $paymentsModel->where('out_trade_no',$order_result['out_trade_no'])->find();
            $this->notify_inner($order['out_trade_no'],$paymentsObj);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success($this->successMsg,$order_result['id']);
    }
    protected function notify_inner($out_trade_no,$paymentsObj)
    {
        $orderObj = $this->model->get($paymentsObj['order_id']);
        if ($orderObj['driver_number'] == 1) {
            if ($orderObj['state'] == 'unpaid') {
                $order_data_update = array(
                    'state'=>'pending',
                );
            }
            if ($orderObj['state'] == 'awaiting_payment') {
                $order_data_update = array(
                    'state'=>'completed',
                    'pay_amount'=>bcadd($orderObj['pay_amount'],$paymentsObj['pay_amount'],2),
                    'completion_time'=>date('Y-m-d H:i:s',time()),
                );
            }

            Db::startTrans();
            try {
                $orderObj->save($order_data_update);
                $paymentsObj['pay_time'] = time();
                $paymentsObj['payment_status'] = 'completed';
                $paymentsObj->save();
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        } else {
            $newPayAmount = bcdiv($orderObj['pay_amount'],$orderObj['driver_number'],2);
            $newEstimatedAmount = bcdiv($orderObj['estimated_amount'],$orderObj['driver_number'],2);
            $newOrderData = array(
                'wechat_id'=>$orderObj['wechat_id'],
                'type'=>$orderObj['type'],
                'city_id'=>$orderObj['city_id'],
                'city'=>$orderObj['city'],
                'from_address'=>$orderObj['from_address'],
                'from_lat'=>$orderObj['from_lat'],
                'from_lng'=>$orderObj['from_lng'],
                'to_address'=>$orderObj['to_address'],
                'to_lat'=>$orderObj['to_lat'],
                'to_lng'=>$orderObj['to_lng'],
                'order_no'=>$orderObj['order_no'],
                'departure_time'=>$orderObj['departure_time'],
                'estimated_amount'=>$newEstimatedAmount,
                'remarks'=>$orderObj['remarks'],
                'driver_number'=>1,
                'pay_amount'=>$newPayAmount,
                'createtime'=>$orderObj['createtime'],
                'state'=>'pending',
                'passenger_id'=>$orderObj['passenger_id'],
                'driving_distance'=>$orderObj['driving_distance'],
                'driving_distance_meter'=>$orderObj['driving_distance_meter'],
                'travel_time'=>$orderObj['travel_time'],
                'platform_commission'=>bcdiv($orderObj['platform_commission'],$orderObj['driver_number'],2),
                'actual_amount'=>$newEstimatedAmount,
            );
            $list = [];
            $paymentsList = [];
            $payments_data = array(
                'out_trade_no'=>$out_trade_no,
                'pay_amount'=>bcdiv($orderObj['pay_amount'],$orderObj['driver_number'],2),
                'payment_type'=>'prepaid',
                'payment_status'=>'completed',
                'pay_time'=>time(),
            );
            for ($i = 1; $i <= $orderObj['driver_number']; $i++) {
                $list[] = $newOrderData;
                $paymentsList[] = $payments_data;
            }

            $paymentsModel = new Payments();
            Db::startTrans();
            try {
                $orderList = $this->model->saveAll($list);
                $orderIdArray = array_column(collection($orderList)->toArray(),'id');
                array_walk($orderIdArray, function(&$value) {
                    // 修改键名逻辑：将键名转换为大写
                    $newKey = 'order_id';
                    $value = [$newKey => $value];
                });
                $paymentsList = array_map(function($row1, $row2) {
                    return array_merge($row1, $row2);
                }, $paymentsList,$orderIdArray);
                $paymentsModel->saveAll($paymentsList);
                $orderObj->delete();
                $paymentsObj->delete();
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

    }

    /**
     * Desc 订单列表
     * Create on 2024/10/22 10:41
     * Create by wangyafang
     */
    public function index()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->get();
        $wechat_id = User::getWechatId($this->auth->id);
        $where['wechat_id'] = array('eq',$wechat_id);


        if(isset($param['state']) && !empty($param['state'])) {
            if ($param['state'] == 'in_progress') {
                $where['state'] = array('in',['accepted','in_progress']);
            } else {
                $where['state'] = array('eq',$param['state']);
            }
        } else {
            $where['state'] = array('in',['pending','accepted','in_progress','adjusting','awaiting_payment','completed','cancelled','refunded']);
        }

        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $count = $this->model->where($where)->count();
        $order = 'id desc';

        $data = $this->model
            ->where($where)
            ->page($page,$limit)
            ->field('id,departure_time,state,actual_amount,from_address,to_address,type,driver_arrive_status')
            ->order($order)
            ->select();

        $evaluationModel = new Evaluation();
        foreach ($data as $v) {
            $evaluationObj = $evaluationModel->where('order_id',$v['id'])->find();
            $v->evaluation_state = $evaluationObj ? 1 : 2;
        }

        $this->success('请求成功',['total'=>$count,'data'=>$data]);
    }

    /**
     * Desc 订单详情
     * Create on 2024/10/25 15:59
     * Create by wangyafang
     */
    public function details()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $id = $this->request->get('id');
        if (empty($id)) {
            $this->error('请输入订单ID');
        }
        $orderObj = $param = $this->model->get($id);
        if (!$orderObj) {
            $this->error('订单不存在');
        }

        $data = array();


        switch ($orderObj['state']) {
            case 'cancelled':
            case 'pending'://待接单
                $estimated_time = \app\api\model\wddj\usert\Order::acceptanceDetails($orderObj);
                $mapResult = (new Map())->get_driver_routes($param);
                $routes = $mapResult['result']['routes'];
                $data = array(
                    'from_address'=>$orderObj['from_address'],
                    'from_lat'=>$orderObj['from_lat'],
                    'from_lng'=>$orderObj['from_lng'],
                    'to_address'=>$orderObj['to_address'],
                    'to_lat'=>$orderObj['to_lat'],
                    'to_lng'=>$orderObj['to_lng'],
                    'estimated_time'=>$estimated_time,
                    'state'=>$orderObj['state'],
                    'routes'=>$routes,
                );
                break;
            case 'accepted'://已接单
                $acceptedObj = $this->model->get($id);
                $driverObj = (new Driver())->get($orderObj['driver_id']);
                $param['from_lat'] = $driverObj['driver_lat'];//出发地纬度
                $param['from_lng'] = $driverObj['driver_lng'];

                $param['to_lat'] = $acceptedObj['from_lat'];//司机当前纬度
                $param['to_lng'] = $acceptedObj['from_lng'];
                $mapResult = (new Map())->get_driver_routes($param);
                $routes = $mapResult['result']['routes'];
                $driver_info = Driver::getDriverBaseInfo($orderObj['driver_id']);
                $driver_info['mobile'] = Driver::getMobile($orderObj['driver_id']);
                $data = array(
                    'from_lat'=>$driverObj['driver_lat'],
                    'from_lng'=>$driverObj['driver_lng'],
                    'to_lat'=>$acceptedObj['from_lat'],
                    'to_lng'=>$acceptedObj['from_lng'],
                    'driver_info'=>$driver_info,
                    'state'=>$orderObj['state'],
                    'routes'=>$routes,
                );
                $data['waiting_start_time' ] = $orderObj['arrive_time'];
                break;
            case 'in_progress'://行驶中
                $driverObj = (new Driver())->get($orderObj['driver_id']);
                $param['from_lat'] = $driverObj['driver_lat'];//司机当前纬度
                $param['from_lng'] = $driverObj['driver_lng'];
                $mapResult = (new Map())->get_driver_routes($param);
                $routes = $mapResult['result']['routes'];
                $driver_info = Driver::getDriverBaseInfo($orderObj['driver_id']);
                $driver_info['mobile'] = Driver::getMobile($orderObj['driver_id']);
                $data = array(
                    'from_address'=>$orderObj['from_address'],
                    'from_lat'=>$driverObj['driver_lat'],
                    'from_lng'=>$driverObj['driver_lng'],
                    'to_address'=>$orderObj['to_address'],
                    'to_lat'=>$orderObj['to_lat'],
                    'to_lng'=>$orderObj['to_lng'],
                    'driver_info'=>$driver_info,
                    'pay_amount'=>$orderObj['pay_amount'],
                    'passenger_info'=> !empty($orderObj['passenger_id']) ? \app\api\model\wddj\usert\Order::getPassenger($orderObj['passenger_id']) : '',
                    'remarks'=>$orderObj['remarks'],
                    'state'=>$orderObj['state'],
                    'routes'=>$routes,
                );
                break;
            case 'adjusting'://行驶结束
            case 'refunded'://行驶结束
            case 'awaiting_payment'://行驶结束
            case 'completed'://行驶结束
            case 'refunded':
                $mapResult = (new Map())->get_driver_routes($param);
                $routes = $mapResult['result']['routes'];
                $driver_info = Driver::getDriverBaseInfo($orderObj['driver_id']);
                $driver_info['mobile'] = Driver::getMobile($orderObj['driver_id']);
                $evaluationModel = new Evaluation();
                $evaluationObj = $evaluationModel->where('order_id',$id)->find();
                $data = array(
                    'from_lat'=>$orderObj['from_lat'],
                    'from_lng'=>$orderObj['from_lng'],
                    'to_lat'=>$orderObj['to_lat'],
                    'to_lng'=>$orderObj['to_lng'],
                    'driver_info'=>$driver_info,
                    'pay_amount'=>$orderObj['pay_amount'],
                    'evaluation_state'=>$evaluationObj ? 1 : 2,
                    'state'=>$orderObj['state'],
                    'routes'=>$routes,
                );
                break;
        }
        $data['driver_arrive_status'] = $orderObj['driver_arrive_status'];
        $data['departure_time'] = $orderObj['departure_time'];
        $data['adjust_amount'] = abs($orderObj['adjust_amount']);
        $data['actual_amount'] = abs($orderObj['actual_amount']);
        $data['from_address'] = $orderObj['from_address'];
        $data['to_address'] = $orderObj['to_address'];

        $this->success('请求成功',$data);
    }

    /**
     * Desc 取消订单
     * Create on 2024/10/22 10:42
     * Create by wangyafang
     */
    public function cancel()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $id = $this->request->post('id');
        if (empty($id)) {
            $this->error('请输入订单ID');
        }
        $orderObj = $this->model->get($id);
        if (!$orderObj) {
            $this->error('订单信息不存在');
        }
        $wechat_id = User::getWechatId($this->auth->id);
        if ($orderObj['wechat_id'] != $wechat_id) {
            $this->error('不是本人，无法操作');
        }
        if ($orderObj['state'] == 'cancelled') {
            $this->error('已取消订单');
        }
        if (!in_array($orderObj['state'],['pending','accepted'])) {
            $this->error('不是待接单和已接单状态，无法操作');
        }
        $cancel_order_reason = isset($param['cancel_order_reason']) ? $param['cancel_order_reason'] : '';

        $refund_no = wddj_create_order();
        $res=\addons\wddj\library\Wxapp::payRefund($orderObj->order_no,$refund_no,$orderObj->pay_amount,array('refund_desc'=>'退款'));

        if($res && $res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            $refundsModel = new Refunds();
            Db::startTrans();
            try {
                $refund_data = array(
                    'order_id'=>$id,
                    'refund_amount'=>$orderObj['pay_amount'],
                    'refund_no'=>$refund_no,
                    'refund_time'=>time(),
                    'reason'=>'用户取消订单',
                );
                $refundsModel->data($refund_data);
                $refundsModel->allowField(true)->save();
                $orderObj->state = 'cancelled';
                $orderObj->cancel_order_reason = $cancel_order_reason;
                $orderObj->save();
                (new Chat())->where('order_id',$id)->where('driver_wechat_id',$orderObj['wechat_id'])->delete();
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('退款操作成功');
        }else{
            $this->error('退款失败,错误信息：'.$res['return_msg']);
        }
    }

    /**
     * Desc 用户待接单数量
     * Create on 2024/12/2 14:01
     * Create by wangyafang
     */
    public function pending_count()
    {
        $wechat_id = User::getWechatId($this->auth->id);
        $count = $this->model->where('wechat_id',$wechat_id)
            ->where('state','pending')
            ->count();
        $this->success('请求成功',array(
            'count'=>$count
        ));
    }

    /**
     * Desc 费用疑问
     * Create on 2024/12/3 10:01
     * Create by wangyafang
     */
    public function cost_inquiry()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $id = $this->request->get('id');

        $orderObj = $this->model->where('id',$id)->field('estimated_amount,actual_amount,city_id,driving_distance_meter,actual_meter')->find();

        if (!$orderObj) {
            $this->error('订单不存在');
        }

        $data['estimated_amount'] = $orderObj['estimated_amount'];
        $data['actual_amount'] = $orderObj['actual_amount'];

        $estimated_amount_result = \app\api\model\wddj\usert\operation\CostAllocation::estimated_amount($orderObj['city_id'],$orderObj['driving_distance_meter']);
        $actual_amount_result = \app\api\model\wddj\usert\operation\CostAllocation::estimated_amount($orderObj['city_id'],$orderObj['actual_meter'],$id);
        $starting_price = array(
            'estimated_amount'=>$estimated_amount_result['estimated_amount_details'][0]['price'].'元',
            'actual_amount'=>$actual_amount_result['estimated_amount_details'][0]['price'].'元',
        );

        $mileage_fee = array();

        if (isset($estimated_amount_result['estimated_amount_details'][1]) || isset($actual_amount_result['estimated_amount_details'][1])) {
            if (isset($estimated_amount_result['estimated_amount_details'][1])) {
                $mileage_fee['estimated']['kilometer'] = $estimated_amount_result['estimated_amount_details'][1]['mileage_fee_kilometer'].'公里';
                $mileage_fee['estimated']['price'] = $estimated_amount_result['estimated_amount_details'][1]['price'].'元';
            } else {
                $mileage_fee['estimated']['kilometer'] = '0.0公里';
                $mileage_fee['estimated']['price'] = '0.00元';
            }

            if (isset($actual_amount_result['estimated_amount_details'][1])) {
                $mileage_fee['actual']['kilometer'] = $actual_amount_result['estimated_amount_details'][1]['mileage_fee_kilometer'].'公里';
                $mileage_fee['actual']['price'] = $actual_amount_result['estimated_amount_details'][1]['price'].'元';
            } else {
                $mileage_fee['actual']['kilometer'] = '0.0公里';
                $mileage_fee['actual']['price'] = '0.00元';
            }
        }

        $total_minute = (new WaitingTime())->where('order_id',$id)->where('minute','>',0)->sum('minute');

        if (!empty($starting_price)) {
            $data = array_merge($data,array(
                'start_price'=>$starting_price,
            ));
        }

        if (!empty($mileage_fee)) {
            $data = array_merge($data,array(
                'mileage_fee'=>$mileage_fee,
            ));
        }

        if (!empty($total_minute)) {
            $duration_price = (new CostAllocation())->where('city_id',$orderObj['city_id'])->value('duration_price');
            $price = bcmul($duration_price,$total_minute,2);
            $data['duration_fee'] = array(
                'estimated'=>array(
                    'price'=>'0.00元',
                    'minute'=>'0分钟',
                ),
                'actual'=>array(
                    'price'=>$price.'元',
                    'minute'=>$total_minute.'分钟',
                ),
            );
        }

        $this->success('请求成功',$data);
    }

}



 